// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/vector/decoded_vector.h>

namespace kumo::pollux::aggregate {
    /// Class to compute hashes identical to one produced by Presto.
    /// Requires the type of the vector to initialize it, after which it can be
    /// reused for several vectors of the same type.
    class PrestoHasher {
    public:
        explicit PrestoHasher(TypePtr type) : type_(std::move(type)) {
            createChildren();
        }

        /// Computes a hash identical to the one used by Presto checksum. The
        /// algorithm is based on XXHash64. Takes a Vector and a SelectivityVector of
        /// rows to be hashed. The type of the vector must be same as used in the
        /// constructor. The resultant hashes are saved in BufferPtr hashes, which
        /// must have as much capacity as sizeof(int64_t) * rows.end().
        void hash(
            const VectorPtr &vector,
            const SelectivityVector &rows,
            BufferPtr &hashes);

    private:
        template<TypeKind kind>
        void hash(const SelectivityVector &rows, BufferPtr &hashes);

        void createChildren();

        std::shared_ptr<DecodedVector> vector_{std::make_shared<DecodedVector>()};
        std::vector<std::unique_ptr<PrestoHasher> > children_;
        const TypePtr type_;
    };
} // namespace kumo::pollux::aggregate
